<?php
declare (strict_types = 1);

namespace app\common\logic;

use think\facade\Db;

class SeckillLogic
{
    /**
     * 获取秒杀商品列表
     * @param array $where 查询条件
     * @return array
     */
    public function getSeckillList($where = [])
    {
        $list = Db::name('seckill_product')->alias('s')
            ->join('goods g', 'g.id = s.goods_id')
            ->where($where)
            ->field('s.*, g.title, g.image, g.description')
            ->select()
            ->toArray();
            
        foreach ($list as &$item) {
            $item['price_info'] = json_decode($item['price'], true);
            $item['status_text'] = $this->getStatusText($item);
        }
        
        return ['status' => 1, 'msg' => '', 'data' => $list];
    }
    
    /**
     * 获取秒杀商品详情
     * @param int $id 秒杀商品ID
     * @return array
     */
    public function getSeckillDetail($id)
    {
        $detail = Db::name('seckill_product')->alias('s')
            ->join('goods g', 'g.id = s.goods_id')
            ->where('s.id', $id)
            ->field('s.*, g.title, g.image, g.description, g.content')
            ->find();
            
        if (empty($detail)) {
            return ['status' => 0, 'msg' => '商品不存在'];
        }
        
        $detail['price_info'] = json_decode($detail['price'], true);
        $detail['status_text'] = $this->getStatusText($detail);
        
        return ['status' => 1, 'msg' => '', 'data' => $detail];
    }
    
    /**
     * 检查秒杀活动状态
     * @param int $seckill_id 秒杀商品ID
     * @return array
     */
    public function checkSeckillStatus($seckill_id)
    {
        $seckill = Db::name('seckill_product')
            ->where(['id' => $seckill_id, 'status' => 1])
            ->lock(true)
            ->find();

        if (empty($seckill)) {
            return ['status' => false, 'msg' => '秒杀活动不存在', 'data' => []];
        }

        $now = time();
        if ($now < $seckill['stime']) {
            return ['status' => false, 'msg' => '秒杀活动未开始', 'data' => []];
        }
        if ($now > $seckill['etime']) {
            return ['status' => false, 'msg' => '秒杀活动已结束', 'data' => []];
        }

        return ['status' => true, 'msg' => '秒杀活动有效', 'data' => $seckill];
    }

    /**
     * 检查购买限制
     * @param int $seckill_id 秒杀商品ID
     * @param int $user_id 用户ID
     * @return array
     */
    public function checkPurchaseLimit($seckill_id, $user_id)
    {
        $bought_count = Db::name('order')
            ->where([
                'user_id' => $user_id,
                'seckill_id' => $seckill_id,
                'status' => ['<>', -1]
            ])
            ->count();

        if ($bought_count > 0) {
            return ['status' => false, 'msg' => '您已参与过该秒杀活动', 'data' => []];
        }

        return ['status' => true, 'msg' => '可以购买', 'data' => []];
    }

    /**
     * 创建秒杀订单
     * @param array $seckill 秒杀商品信息
     * @param int $user_id 用户ID
     * @param int $num 购买数量
     * @return array
     */
    public function createOrder($seckill, $user_id, $num = 1)
    {
        if ($seckill['stock'] < $num) {
            return ['status' => false, 'msg' => '商品库存不足', 'data' => []];
        }

        // 更新库存
        $result = Db::name('seckill_product')
            ->where(['id' => $seckill['id'], 'stock' => ['>=', $num]])
            ->dec('stock', $num)
            ->update();

        if (!$result) {
            return ['status' => false, 'msg' => '库存更新失败', 'data' => []];
        }

        // 创建订单
        $price_info = json_decode($seckill['price'], true);
        $order_data = [
            'order_no' => $this->generateOrderNo(),
            'user_id' => $user_id,
            'seckill_id' => $seckill['id'],
            'goods_id' => $seckill['goods_id'],
            'goods_name' => $seckill['name'],
            'goods_num' => $num,
            'goods_price' => $price_info['seckill_price'],
            'order_amount' => $price_info['seckill_price'] * $num,
            'add_time' => time(),
            'order_status' => 0 // 待支付
        ];

        $order_id = Db::name('order')->insertGetId($order_data);
        if (!$order_id) {
            return ['status' => false, 'msg' => '订单创建失败', 'data' => []];
        }

        return ['status' => true, 'msg' => '下单成功', 'data' => ['order_id' => $order_id]];
    }
    
    /**
     * 获取秒杀状态文本
     * @param array $seckill 秒杀商品信息
     * @return string
     */
    private function getStatusText($seckill)
    {
        $now = time();
        if ($seckill['status'] != 1) {
            return '已结束';
        }
        if ($now < $seckill['stime']) {
            return '未开始';
        }
        if ($now > $seckill['etime']) {
            return '已结束';
        }
        if ($seckill['stock'] <= 0) {
            return '已抢完';
        }
        return '抢购中';
    }
    
    /**
     * 生成订单号
     * @return string
     */
    private function generateOrderNo()
    {
        return date('YmdHis') . mt_rand(1000, 9999);
    }
}